import re
from string import maketrans
from google.appengine.ext import db

class LabelInfo(db.Model):
    label = db.StringProperty(required=True)
    documents = db.ListProperty(db.Key, required=True)
    topics = db.StringListProperty(required=True)

    def __init__(self, *args, **kwargs):
        if not 'key' in kwargs:
            kwargs['key_name'] = kwargs['label']
        db.Model.__init__(self, *args, **kwargs)

    def is_empty(self):
        return (len(self.documents) == 0 and len(self.topics) == 0)

    def add_document(self, key):
        self.documents.append(key)

    def remove_document(self, key):
        if self.douments.has_key(key):
            self.documents.remove(key)

    def add_topic(self, topic):
        if not topic in self.topics:
            self.topics.append(topic)

    def remove_topic(self, topic):
        if self.topics.has_key(topic):
            self.topics.remove(topic)


class LabelInfos(dict):
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = LabelInfo(label = item)
            return value

class LabelUtils:
    label_to_pretty = None

    @staticmethod
    def PrettifyLabel(label):
        if (LabelUtils.label_to_pretty == None):
            LabelUtils.label_to_pretty = {}
            for line in open("glp/library/labels.txt", "r").readlines():
                data = line.rstrip('\r\n').split(' ', 1)
                LabelUtils.label_to_pretty[data[0]] = data[1]
        return LabelUtils.label_to_pretty.get(label, label)

    # Note: this must match label-topic-box.js/clean_label()
    @staticmethod
    def CleanLabels(dirty):
        clean = []
        clean_table = maketrans(' /','--')
        for label in dirty:
            clean_label = unicode(label.lower().translate(clean_table, "')("))
            if len(clean_label) == 0: continue
            clean.append(clean_label)
        return clean

    @staticmethod
    def ComputeLabelTopics(document):
        topic_labels = document.topic_labels()
        other_labels = filter(lambda label: not label.startswith('topic:'), document.labels)
        label_topics = []
        for topic_label in topic_labels:
            label_topics.append(('-', topic_label))
            for other_label in other_labels:
                label_topics.append((other_label, topic_label))
        return label_topics
